import requests  # 导http请求包（用于网络接口调用）
import json                                         # 导入json模块

# 扣子官方文件上传返回文件ID
def upload_image(access_token, file_path):
    # 接口地址
    url = "https://api.coze.cn/v1/files/upload"

    # 设置请求头（需包含访问令牌）
    headers = {
        "Authorization": f"Bearer {access_token}"
    }

    try:
        # 使用 with 语句打开文件，确保文件在使用完后自动关闭
        with open(file_path, "rb") as file:
            # 构造文件上传参数（multipart/form-data格式）
            files = {
                "file": file  # 键名"file"与接口要求一致
            }

            # 发送POST请求
            response = requests.post(url, headers=headers, files=files)
            result = response.json()

            # 处理响应结果
            if result.get("code") == 0:
                print("[文件] 上传成功，文件ID:", result['data']['id'])
                file_id = result['data']['id']
                return file_id
            else:
                print(f"[错误] 上传失败：{result['msg']}")
                return None
    except requests.RequestException as e:
        print(f"[错误] 网络请求出现错误: {e}")
        return None
    except Exception as e:
        print(f"[错误] 上传出现未知错误: {e}")
        return None


# 调用扣子客服工作流
def call_workflow(access_token, workflow_id, app_token,my_id,my_name,username,xhs_id,user_id,Chat_screenshot):
    # 接口地址
    url = 'https://api.coze.cn/v1/workflow/run'

    # 请求头
    headers = {
        'Authorization': f'Bearer {access_token}',
        'Content-Type': 'application/json'
    }

    # 请求体
    data = {
        "parameters": {
            # 将file_id列表转换为对象数组格式
            "app_token":app_token,
            "my_id": my_id,
            "my_name": my_name,
            "username":username,
            "xhs_id":xhs_id,
            "user_id":user_id,
            "Chat_screenshot": [{"file_id": fid} for fid in Chat_screenshot]
        },
        "is_async": True,
        "workflow_id": workflow_id
    }



    try:
        # 发送 POST 请求
        response = requests.post(url, headers=headers, json=data)
        response.raise_for_status()  # 检查请求是否成功

        # 打印响应结果 （如果不需要打印，可以注释掉下面两行）
        # print("调用状态码:", response.status_code)
        # print("响应结果:", response.json())

        return response.json()
    except requests.RequestException as e:
        print(f"请求出错: {e}")
        return None
    except ValueError as e:
        print(f"解析响应 JSON 出错: {e}")
        return None
    
# 调用扣子飞书表查询工作流（查客服话术表）
def Query_Feishu_data(access_token, workflow_id, app_token,my_id):
    # 接口地址
    url = 'https://api.coze.cn/v1/workflow/run'

    # 请求头
    headers = {
        'Authorization': f'Bearer {access_token}',
        'Content-Type': 'application/json'
    }

    # 请求体
    data = {
        "parameters": {
            # 将file_id列表转换为对象数组格式
            "app_token":app_token,
            "filter": {
                "conditions": [
                    {
                        "field_name": "my_id",
                        "operator": "is",
                        "value": [
                            my_id
                        ]
                    },
                    {
                        "field_name": "state",
                        "operator": "is",
                        "value": [
                            "待使用"
                        ]
                    }
                ],
                "conjunction": "and"
            }
        },

        "workflow_id": workflow_id
    }



    try:
        # 发送 POST 请求
        response = requests.post(url, headers=headers, json=data)
        response.raise_for_status()  # 检查请求是否成功

        # 打印响应结果 （如果不需要打印，可以注释掉下面两行）
        # print("调用状态码:", response.status_code)
        # print("响应结果:", response.json())

        return response.json()
    except requests.RequestException as e:
        print(f"请求出错: {e}")
        return None
    except ValueError as e:
        print(f"解析响应 JSON 出错: {e}")
        return None


# 调用扣子飞书表查询记录工作流（查配置表）
def Query_config_data(access_token, workflow_id, app_token,Scheme_Name):
    # 接口地址
    url = 'https://api.coze.cn/v1/workflow/run'

    # 请求头
    headers = {
        'Authorization': f'Bearer {access_token}',
        'Content-Type': 'application/json'
    }

    # 请求体
    data = {
        "parameters": {
            # 将file_id列表转换为对象数组格式
            "app_token":app_token,
            "filter": {
                "conditions": [
                    {
                        "field_name": "Scheme_Name",
                        "operator": "is",
                        "value": [
                            Scheme_Name
                        ]
                    }
                ],
                "conjunction": "and"
            }
        },

        "workflow_id": workflow_id
    }



    try:
        # 发送 POST 请求
        response = requests.post(url, headers=headers, json=data)
        response.raise_for_status()  # 检查请求是否成功

        # 打印响应结果 （如果不需要打印，可以注释掉下面两行）
        # print("调用状态码:", response.status_code)
        # print("响应结果:", response.json())

        # 获取配置表中的数据    
        config_data = response.json()
        if config_data and 'data' in config_data and config_data['data']:
            json_data = json.loads(config_data['data'])
            data_list = json_data['data'] 
            return data_list
        
        else:
            return None


    except requests.RequestException as e:
        print(f"请求出错: {e}")
        return None
    except ValueError as e:
        print(f"解析响应 JSON 出错: {e}")
        return None



# 调用扣子飞书表修改记录工作流（修改客服话术表）
def modify_Feishu_data(access_token, workflow_id, app_token,record_id,state):
    # 接口地址
    url = 'https://api.coze.cn/v1/workflow/run'

    # 请求头
    headers = {
        'Authorization': f'Bearer {access_token}',
        'Content-Type': 'application/json'
    }

    # 请求体
    data = {
        "parameters": {
            "app_token": app_token,
            "state": state,
            "record_id": record_id
        },
        "workflow_id": workflow_id
    }

    try:
        # 发送 POST 请求
        response = requests.post(url, headers=headers, json=data)
        response.raise_for_status()  # 检查请求是否成功

        # 打印响应结果 （如果不需要打印，可以注释掉下面两行）
        # print("调用状态码:", response.status_code)
        # print("响应结果:", response.json())

        return response.json()
    except requests.RequestException as e:
        print(f"请求出错: {e}")
        return None
    except ValueError as e:
        print(f"解析响应 JSON 出错: {e}")
        return None
    

# 调用扣子飞书表创建记录工作流（新增报错日志）
def add_log_data(coze_token, adddata_workflow_id, log_app_token, title, content, tag):
    # 接口地址
    url = 'https://api.coze.cn/v1/workflow/run'

    # 请求头
    headers = {
        'Authorization': f'Bearer {coze_token}',
        'Content-Type': 'application/json'
    }

    # 请求体
    data = {
        "parameters": {
            "app_token": log_app_token,
            "records": f"[{{\"fields\":{{\"标题\":\"{title}\",\"内容\":\"{content}\",\"标签\":\"{tag}\"}}}}]",
        },
        "workflow_id": adddata_workflow_id
    }

    try:
        # 发送 POST 请求
        response = requests.post(url, headers=headers, json=data)
        response.raise_for_status()  # 检查请求是否成功

        # 打印响应结果 （如果不需要打印，可以注释掉下面两行）
        # print("调用状态码:", response.status_code)
        # print("响应结果:", response.json())

        return response.json()
    except requests.RequestException as e:
        print(f"请求出错: {e}")
        return None
    except ValueError as e:
        print(f"解析响应 JSON 出错: {e}")
        return None